import React, { useEffect, useState } from 'react';
import { Modal, Input, Button, App } from 'antd';
import { MinusCircleFilled, PlusCircleFilled, CloseOutlined } from '@ant-design/icons';

interface HotQuestion {
  id: string;
  content: string;
  answer?: string;
}

interface HotQuestionModalProps {
  visible: boolean;
  onClose: () => void;
  initialQuestions?: HotQuestion[];
  onSave: (questions: HotQuestion[]) => void;
}

const HotQuestionModal: React.FC<HotQuestionModalProps> = ({
  visible,
  onClose,
  initialQuestions = [],
  onSave,
}) => {
  const { message } = App.useApp();
  const [questions, setQuestions] = useState<HotQuestion[]>(initialQuestions);
  const [newQuestion, setNewQuestion] = useState('');
  const [editingQuestionId, setEditingQuestionId] = useState<string | null>(null);
  const [answeringQuestionId, setAnsweringQuestionId] = useState<string | null>(null);
  const [answerMode, setAnswerMode] = useState<{ [key: string]: boolean }>({});

  useEffect(() => {
    setQuestions(initialQuestions);
    setAnswerMode(initialQuestions.reduce((acc, question) => ({
      ...acc,
      [question.id]: !!question.answer
    }), {}));
  }, [initialQuestions]);

  useEffect(() => {
    if (visible) {
      setQuestions(initialQuestions)
      setNewQuestion('');
    }
  }, [visible]);

  const addQuestion = () => {
    if (!newQuestion.trim()) {
      message.warning('问题内容不能为空');
      return;
    }

    if (questions.length >= 5) {
      message.warning('最多只能添加5个热门问题');
      return;
    }

    // 检查问题是否重复
    const isDuplicate = questions.some(q => q.content === newQuestion.trim());
    if (isDuplicate) {
      message.warning('问题内容不能重复');
      return;
    }

    const newId = Date.now().toString();
    setQuestions([...questions, { id: newId, content: newQuestion }]);
    setNewQuestion('');
  };

  const deleteQuestion = (id: string) => {
    setQuestions(questions.filter(q => q.id !== id));
    setAnswerMode(prev => {
      const newMode = { ...prev };
      delete newMode[id];
      return newMode;
    });
  };

  const updateQuestionContent = (id: string, content: string) => {
    setQuestions(questions.map(q => q.id === id ? { ...q, content } : q));
    setEditingQuestionId(null);
  };

  const updateQuestionAnswer = (id: string, answer: string) => {
    setQuestions(questions.map(q => q.id === id ? { ...q, answer } : q));
  };

  const handleSave = () => {
    let finalQuestions = [...questions];

    // 如果 newQuestion 不为空，添加到问题列表中
    if (newQuestion.trim()) {
      if (finalQuestions.length >= 5) {
        message.warning('最多只能添加5个热门问题');
        return;
      }

      // 检查问题是否重复
      const isDuplicate = finalQuestions.some(q => q.content === newQuestion.trim());
      if (isDuplicate) {
        message.warning('问题内容不能重复');
        return;
      }

      finalQuestions = [...finalQuestions, { id: Date.now().toString(), content: newQuestion.trim() }];
    }

    // 处理答案模式
    finalQuestions = finalQuestions.map(q => ({
      ...q,
      answer: answerMode[q.id] ? q.answer : undefined
    }));

    onSave(finalQuestions);
    setNewQuestion('');
    onClose();
  };

  const toggleAnswerMode = (id: string) => {
    setAnswerMode(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
    if (answerMode[id]) {
      // 如果从添加答案切换到模型回答，清空答案
      updateQuestionAnswer(id, '');
    }
  };

  // 输入框自定义样式
  const inputStyle = {
    background: '#F1F3F9',
    border: 'none',
    borderColor: 'transparent',
    boxShadow: 'none',
    padding: '8px',
    borderRadius: '8px'
  };

  return (
    <Modal
      title={
        <div className="flex flex-col items-left">
          <div className="text-lg font-medium">热门问题</div>
          <div className="font-normal text-[11px] text-[#A5A9BB] mt-1">
            每次对话展示预设问题，最多5个固定的问题，指引用户使用
          </div>
        </div>
      }
      open={visible}
      onCancel={onClose}
      width={610}
      centered
      footer={null}
      closeIcon={<CloseOutlined className="text-[#86909C]" />}
      bodyStyle={{ padding: '24px 0px' }}
    >
      <div>
        {/* 输入新问题 */}
        <div className="mb-4">
          <div className="relative">
            <Input
              placeholder="点击这里输入新的问题，点击回车键（Enter键）确定"
              value={newQuestion}
              onChange={(e) => setNewQuestion(e.target.value)}
              onPressEnter={addQuestion}
              maxLength={50}
              style={inputStyle}
              className="!bg-[#F1F3F9] !border-none"
              prefix={
                <PlusCircleFilled
                  className="text-[#8C8C8C] hover:text-[#1677ff] cursor-pointer"
                  onClick={addQuestion}
                  style={{ marginRight: '8px' }}
                />
              }
              suffix={
                <span className="text-[#8C8C8C] text-xs">
                  {newQuestion.length}/50
                </span>
              }
            />
          </div>
        </div>

        {/* 问题列表 */}
        <div className="mb-6 max-h-[300px] overflow-y-auto">
          {questions.map((question) => (
            <div
              key={question.id}
              className="mb-4 rounded-lg bg-[#F1F3F9]"
            >
              <div className="flex items-center p-2 rounded-lg bg-[#F1F3F9]">
                <MinusCircleFilled
                  className="mr-3 text-[#8C8C8C] hover:text-[#ff4d4f] cursor-pointer"
                  onClick={() => deleteQuestion(question.id)}
                />
                <div className="flex-1 text-[#424242]">
                  <Input
                    value={question.content}
                    onChange={(e) => updateQuestionContent(question.id, e.target.value)}
                    onPressEnter={() => setEditingQuestionId(null)}
                    onBlur={() => setEditingQuestionId(null)}
                    // autoFocus
                    style={{ ...inputStyle, padding: '0px' }}
                    maxLength={50}
                  />
                </div>
                <Button
                  type="link"
                  className="ml-2"
                  style={{ height: 'unset' }}
                  onClick={() => toggleAnswerMode(question.id)}
                >
                  {answerMode[question.id] ? '模型回答' : '添加答案'}
                </Button>
              </div>

              {/* 回答输入区域 */}
              {answerMode[question.id] && (
                <div className="mt-0 ml-8 border-t border-[#D6D6D6] mr-5">
                  <Input.TextArea
                    placeholder="请输入模型回答内容"
                    value={question.answer || ''}
                    onChange={(e) => updateQuestionAnswer(question.id, e.target.value)}
                    autoSize={{ minRows: 2, maxRows: 5 }}
                    style={{ ...inputStyle, paddingLeft: '0px' }}
                    maxLength={200}
                  />
                </div>
              )}
            </div>
          ))}
          {questions.length >= 5 && (
            <div className="text-[#A5A9BB] text-xs mt-1 text-center">
              已达到最大问题数量限制
            </div>
          )}
        </div>

        {/* 底部按钮 */}
        <div className="flex justify-center space-x-16">
          <Button
            onClick={onClose}
          // className="px-6 rounded-full"
          // style={{ minWidth: '120px', height: '40px', borderRadius: '50px' }}
          >
            取消
          </Button>
          <Button
            type="primary"
            onClick={handleSave}
          // className="px-6 rounded-full"
          // style={{ minWidth: '120px', height: '40px', borderRadius: '50px' }}
          >
            保存
          </Button>
        </div>
      </div>
    </Modal>
  );
};

export default HotQuestionModal; 